package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.plugins.Page;
import com.drd.dt.back.service.IUserManageService;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.dao.*;
import com.drd.dt.modular.dto.CreditCardOrder;
import com.drd.dt.modular.dto.CreditCardOrderDTO;
import com.drd.dt.modular.entity.Order;
import com.drd.dt.modular.entity.User;
import com.drd.dt.modular.service.CreditCardService;
import com.drd.dt.util.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 办卡流程
 * 流程描述
 * 1) 用户进入合作商 APP 首页，看到卡多分的入口；
 * 2) 点击卡多分入口，需要有用户的登录信息，即在后台联合登录，然后进入卡多分的首页；
 * 3) 点击分类或银行入口，进入信用卡分类列表页，此页面的佣金显示是根据用户等级计算的；
 * 4) 点击某一张信用卡，进入卡片详情页，页面底部有立即办卡和分享按钮，此页面的佣金显示逻辑同③， 点击“分享赚钱”按钮，可以把卡片详情页分享出去；点击“首页”回到卡多分 SDK 首页；
 * 5) 点击立即办卡，进入银行办卡页面，用户可填写信息办理信用卡，点击 APP 最上面的关闭按钮，可直 接返回到卡多分 SDK 首页。
 * <p>
 * 查询进度流程
 * 流程描述
 * 1) 用户进入合作商 APP 个人中心页，点击“信用卡订单”可以看到“信用卡订单列表。入口位置会有变化,以双方合作商讨决定的为准；
 * 2) 此页面为订单列表页面，仅指用户自己的办卡订单。若贵司希望在用户端展示该用户分享后其他用户 办理的订单，则需要贵司使用自有的用户关联关系，凭用户 id 和卡多分订单 api 查询接口找到被分享 者的订单，然后自组分享者的订单。
 * 3) 查询订单进度
 * a、非终态（完成/拒绝/老户）的订单，用户都可以点击查询进度进入该页面；
 * b、若订单信息中有身份证信息，则用户可正常查询进度，若查询到 审核中、审核通过、审核拒绝， 则该订单的状态也会相应的修改，如图④；
 * c、若订单信息中无身份证信息，进入图⑤进行身份信息的补充，补充完成后继续进行后续操作；
 */

@Service
@Transactional
public class CreditCardServiceImpl implements CreditCardService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserMoneyServiceImpl moneyService;
    @Autowired
    private CreditCardOrderMapper creditCardOrderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserMoneyMapper userMoneyMapper;

    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private OrderMapper orderMapper;


    private final String appkey = "hetaoshengqian"; //应用Appkey


    //测试密钥
//    private final String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHuwfLOLD8VkThi0E01LR05WxLfVdVL/LqJ8Ea1OZAHVjRFzYC11CTr21kEM+Lp/O/Eabj34JEjOg28SMQRTxWWXSwA1Zl0pxtfqFEz7c9to6emZLC3USm6dv/nvS57ffjt0lOCZXvej80m88yAXHTBQP4SY92sR+PiKyuI1cOOwIDAQAB";
//    private String show_url = "https://st-shengbei.smyfinancial.com/kaduofen_h5/app_cardhome?"; //测试地址
//    private String apiUrl = "https://appsttest.smyfinancial.com/cm-front"; //测试地址


    /***卡多分 H5 地址***/
    private String show_url = "https://www.icardfinancial.com/kaduofen_h5/app_cardhome?"; //正式地址
    //正式
    private final String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDP0+OoXPo8m/lZjfyDsC1fRGt4snLx7a5Txn0eC74emgDhFXxHLbzlogG5+P9b6SmxzdGEcDzxYCOtz+ReaGP5m3gT07t9Owzhf34eQQzsCZKQLxbEAwU2aPnVOeTG+auPHmZfKWzTBlN0hXSL5Wsj9CFRI55NKim6S+5ZecFdCQIDAQAB";
    /***查询接口地址***/
    private String apiUrl = "https://icardapp.icardfinancial.com/cm-front"; //正式地址


    @Autowired
    private IUserManageService userManageService;

    @Override
    public Tip creditCardURL(String userId, String bonusRate, String shareRate) throws Exception {
        //1 用户查询
        Map mapuser = new HashMap();
        mapuser.put("id", userId);
        User user = userMoneyMapper.getByUserId(mapuser);
        if (null == user) {
            throw new BussinessException(BizExceptionEnum.USER_MONEY_LOSE);
        } else {
        }

        if (StringUtils.isEmpty(bonusRate) || StringUtils.isEmpty(shareRate)) {
            double rate = moneyService.getRakeBackRatebyUser(user);//返佣比例
            String doublerate = String.format("%.2f", rate);
            bonusRate = Double.valueOf(doublerate) * 100 + "";
            shareRate = Double.valueOf(doublerate) * 100 + "";
        }
        String mobile = user.getPhone();
        //3 生成url
        Tip tip = createSmyToken(userId, mobile, bonusRate, shareRate);
        if (tip.getCode() != 200) {
            throw new BussinessException(BizExceptionEnum.CREATE_SYM_TOKEN);
        }
        String qd = (String) tip.getData();
        String url = show_url + "qd=" + appkey + "&encrypt=" + qd;
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), url);
    }

    public Tip createSmyToken(String userId, String mobile, String bonusRate, String shareRate) throws Exception {

        String token = null;


        //组装请求json对象，参照文档提供对应参数
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("timestamp", Long.toString(System.currentTimeMillis()));
        jsonObj.put("user_id", userId);
        jsonObj.put("mobile", mobile);
        jsonObj.put("bonusRate", bonusRate);
        jsonObj.put("shareRate", shareRate);

        String json = jsonObj.toJSONString();
        try {
            //对请求json进行rsa加密
            byte[] encryptBytes = RsaCoder.encryptByPublicKey(json.getBytes(Charset.forName("UTF-8")), pubKey);

            //base64对加密结果进行编码
            token = new String(Base64.encodeBase64(encryptBytes));
//            System.out.println(token);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BussinessException(BizExceptionEnum.CREATE_SYM_TOKEN);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), token);
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    private String sendPost(String url, String param, Map<String, String> headerMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        HttpsURLConnection conn = null;
        try {

            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, tm, new java.security.SecureRandom());

            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            // 打开和URL之间的连接
            URL realUrl = new URL(url);
            conn = (HttpsURLConnection) realUrl.openConnection();
            conn.setSSLSocketFactory(ssf);


            // 设置通用的请求属性
            Iterator<Map.Entry<String, String>> it = headerMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> entry = it.next();
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("accept", "application/json");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
//            System.out.println("-----result-----" + result);
        } catch (Exception e) {
//            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /***
     * 查询单个应用信用卡订单
     * 接口 /b2b/api/getOrderListBysupplier
     * */
    @Override
    public Tip adhibitionCreditCardOrder(int dataFlag, String startDate, String endDate, int pageNo, int pageSize) throws Exception {
        String url = "/b2b/api/getOrderListBysupplier";
        JSONObject object = new JSONObject();
        object.put("dataFlag", dataFlag);
        object.put("startDate", startDate);
        object.put("endDate", endDate);
        object.put("pageNo", pageNo);
        object.put("pageSize", pageSize);
        String data = getData(object, url);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), data);
    }

    /***
     * 查询单个用户信用卡订单
     * 接口 /b2b/api/getOrderListByOpenId
     * */
    @Override
    public Tip userCreditCardOrder(int user_id) throws Exception {
        String url = "/b2b/api/getOrderListByOpenId";
        JSONObject object = new JSONObject();
        object.put("openId", user_id);
        String data = getData(object, url);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), data);
    }


    /**
     * 信用卡回调  applyStatus
     * 001	待查询	非订单终态，需要用户进行进度查询更新
     * 002	审核中	非订单终态，需要用户进行进度查询更新
     * 003	审核通过	仅表示在银行端存在审批通过记录
     * 004	审核拒绝	银行拒绝了用户的信用卡申请
     * 005	未完件	用户未正常完成资料填写，也可能是系统误判，补充三要素后可以正常进行查询进度
     * 006	异常订单	某些未知原因造成的订单异常，该种订单很可能需要后续走卡多分的人工流程进 行订单情况的核实
     * 007	失效订单	处于待查询/未完件/异常订单且距离创建订单的日期超过45天
     */
    @Override
    public Tip notification(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream inStream = null;
        ByteArrayOutputStream outSteam = null;
        try {
            logger.info("【开始接收卡多分回调结果...】");
            response.setContentType("text/html");
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            inStream = request.getInputStream();
            outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }


            String result = new String(outSteam.toByteArray(), "utf-8");
            System.out.println("result：" + result);
//            result = "{\"issueFlag\":\"N\",\"custNo\":\"180001047106\",\"cardIcon\":\"https://www.beshtech.com//prodata/aasnew/app02/shop/20190417/5a2ab2e1-0f37-4d1d-885f-022342d6d593.png\",\"shareRate\":0.0,\"supplierBonus\":60.0,\"bankIcon\":\"https://www.beshtech.com//prodata/aasnew/app01/shop/20190322/660144b7-0b1c-4370-8738-3306609f6c23.png\",\"applyDatetime\":1578478066080,\"cardProgressSwitch\":\"1\",\"orgBonus\":60.0,\"applyStatus\":\"005\",\"crawlId\":\"/crawl/projects/banka/jianshe\",\"id\":\"C462001080005900003\",\"currencyName\":\"元\",\"cardName\":\"信用卡\",\"createDatetime\":1578478066080,\"completionFlag\":\"0\",\"idNo\":\"510802********5419\",\"cardId\":\"C671903220000160001\",\"orderType\":\"T00\",\"updateDatetime\":1578478066080,\"supplierCustNo\":\"100504\",\"remittanceFlag\":\"N\",\"bonusRate\":0.0,\"bankName\":\"建设银行\",\"bankCode\":\"01050000\",\"cardChannelLink\":\"http://m.ccb.com/cn/creditcard/mobilev3/cards/product_list.html?Rcmd_insID=A00000149\",\"bonus\":60.0,\"isOutStock\":\"2\",\"custName\":\"*璃珠\",\"addProgressInfo\":\"N\",\"newUserFlag\":\"1\",\"mobileNo\":\"173****2155\"}";
            JSONObject jsonObject = JSONObject.parseObject(result);
            Map<String, Object> reqMap = JSONObject.parseObject(jsonObject.toJSONString(), new TypeReference<Map<String, Object>>() {
            });

            String issueFlag = "";
            String applyStatus = ""; //订单状态 000 老户订单 001 带查询 002审核中 003审核通过 004 审核拒绝 005 未完成 006 异常订单
            if (reqMap.containsKey("applyStatus")) {
                applyStatus = (String) reqMap.get("applyStatus");
            }
            if (reqMap.containsKey("issueFlag")) {
                issueFlag = (String) reqMap.get("issueFlag");
            }

            Map<String, Object> parm = new HashMap<String, Object>();
            String custNo = null;  //客户号
            String id = null;  //客户号
            String supplierCustNo = null;// 合作伙伴客户号，用户唯一标识符,即userId'
            Long createDatetime = null;//创建时间
            Long updateDateTime = null;//修改时间
            String bankName = null;// 银行名称
            String cardId = null;//信用卡类型ID
            String cardIcon = null;// 银行图标
            if (reqMap.containsKey("id")) {
                id = (String) reqMap.get("id");
            }
            if (reqMap.containsKey("custNo")) {
                custNo = (String) reqMap.get("custNo");
            }
            if (reqMap.containsKey("supplierCustNo")) {
                supplierCustNo = (String) reqMap.get("supplierCustNo");
            }
            if (reqMap.containsKey("createDatetime")) {
                createDatetime = (Long) reqMap.get("createDatetime");
            }
            if (reqMap.containsKey("updateDateTime")) {
                updateDateTime = (Long) reqMap.get("updateDateTime");
            }
            if (reqMap.containsKey("bankName")) {
                bankName = (String) reqMap.get("bankName");
            }
            if (reqMap.containsKey("cardId")) {
                cardId = (String) reqMap.get("cardId");
            }
            if (reqMap.containsKey("cardIcon")) {
                cardIcon = (String) reqMap.get("cardIcon");
            }

            if (null == supplierCustNo || supplierCustNo.equals("")) {
                throw new BussinessException(BizExceptionEnum.USER_ID_DISAPPEAR);
            }

            parm.put("id", id);
            parm.put("supplierCustNo", supplierCustNo);

            //1 判定用户当前状态是否与订单状态相同，不相同 则更新订单 状态(防止重复更新 提示：卡多分 回调三次)
            CreditCardOrder creditCardOrder = creditCardOrderMapper.selectAll(parm);
            if (creditCardOrder == null) {
                System.out.println("订单不存在：需要新增");
                //1.1 不存在新增
                System.out.println("req:" + reqMap.toString());
                int req = creditCardOrderMapper.insertCreditCardOrder(reqMap);
                if (req < 1) {
                    throw new BussinessException(BizExceptionEnum.ADD_ERROR);
                }
                System.out.println("订单不存在：新增成功");

                //1.2 存入order 走返佣流程
                String orderId = id;
                String userId = supplierCustNo;
                BigDecimal bonus = null;
                if (reqMap.containsKey("bonus")) {
                    if (reqMap.get("bonus") instanceof Integer) {
                        bonus = new BigDecimal(((Integer) reqMap.get("bonus")).toString());
                        ;
                    }
                    if (reqMap.get("bonus") instanceof BigDecimal) {
                        bonus = (BigDecimal) reqMap.get("bonus");
                    }
                }
                logger.info("核桃省钱信用卡订单客户号ID为：【" + orderId + "】的订单不存在，开始新增...");
                Order createOrder = new Order();
                createOrder.setBuytype(0); //购买类型 ：0自购 ，1来自分享
                Map mapuser = new HashMap();
                mapuser.put("id", userId);
                User myuser = userMoneyMapper.getByUserId(mapuser);

                if (null != myuser) {
                    Integer userid = myuser.getId();
                    String channel_id = myuser.getChannel_id();
                    createOrder.setUser_id(userid);
                    createOrder.setChannel_id(channel_id);
                    createOrder.setTaobao_rid("");
                    createOrder.setTaobao_sid("");
                    createOrder.setRedpacket(0);//无法使用红包
                }

                if (createOrder != null && null != myuser) {
                    createOrder.setNumber(1);
                    createOrder.setProduct_id(cardId);
                    createOrder.setProduct_name(bankName);
                    createOrder.setActual_amount("0");
                    createOrder.setProduct_pic_url(cardIcon);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time = sdf.format(createDatetime).toString();
                    createOrder.setCreate_time(time);
                    createOrder.setOrder_id(orderId);
                    Double rate = moneyService.getRakeBackRatebyUser(myuser);//返佣比例
                    String doublerate = String.format("%.2f", rate);
                    createOrder.setUser_rake(Double.parseDouble(doublerate) + "");
                    createOrder.setUser_rake_back_yugu(bonus + "");
                    createOrder.setRake_back(bonus + "");//返佣
                    createOrder.setUser_rake_back(bonus.doubleValue() / Double.parseDouble(doublerate) + "");//用户返佣

                    /***
                     * 卡多分订单状态： 000 老户订单 001 带查询 002审核中 003审核通过 004 审核拒绝 005 未完成 006 异常订单
                     *
                     * jz_order 订单状态： 1-订单结算 2-订单付款 3-订单未付款 4-订单失效
                     *            当type = 10   ,1订单结算 2 审核通过，3 审核中 ， 4 审核不 通过 5带查询  6未完成7 异常订单 8 失效订单
                     * */
                    if (applyStatus.equals("000") || applyStatus.equals("005")) {
                        createOrder.setStatus(6);
                    } else if (applyStatus.equals("001")) {
                        createOrder.setStatus(5);
                    } else if (applyStatus.equals("002")) {
                        createOrder.setStatus(3);
                    } else if (applyStatus.equals("003")) {
                        createOrder.setStatus(2);
                    } else if (applyStatus.equals("004")) {
                        createOrder.setStatus(4);
                    } else if (applyStatus.equals("006")) {
                        createOrder.setStatus(7);
                    } else {
                        createOrder.setStatus(8);
                    }

                    createOrder.setType(10); //订单类型 1淘宝,2京东，3拼多多，4唯品会 （10信用卡）',
                    orderMapper.insert(createOrder);//新增ORDER记录
                    if (null != myuser && createOrder != null) {
                        moneyService.updateOrderFansRake(myuser, createOrder);//新增加订单
                    } else {
                        logger.info("【淘宝新增信用卡订单用户为空：" + orderId + "】");
                    }
                }
                System.out.println("新增返佣逻辑走完");
            } else {
                System.out.println("订单存在：需要根据订单状态做逻辑：" + applyStatus);
                custNo = creditCardOrder.getCust_no();
                id = creditCardOrder.getId();
                supplierCustNo = creditCardOrder.getSupplier_cust_no();
                createDatetime = creditCardOrder.getCreate_date_time();
                updateDateTime = creditCardOrder.getUpdate_date_time();
                Double bonus = creditCardOrder.getBonus();
                Integer user_id = Integer.parseInt(supplierCustNo);

                //1.1 存在 根据状态  相同 不做任何处理
                if (!creditCardOrder.getApply_status().equals(applyStatus)) {
                    //1.1.1 更新状态
                    int req = creditCardOrderMapper.updateStatue(supplierCustNo, id, applyStatus, "" + updateDateTime);
                    if (req < 1) {
                        throw new BussinessException(BizExceptionEnum.UPDATE_ERROR);
                    }
                    System.out.println("订单存在-订单与数据库不相同:更新状态成功");
                    //1.2  不同 根据状态反应  订单状态 000 老户订单 001 带查询 002审核中 003审核通过 004 审核拒绝 005 未完成 006 异常订单
                    //1.2.1 判定用户 是否有佣金  需要分佣金 需要计算
                    if (applyStatus.equals("003") && issueFlag.equals("Y")) {//applyStatus=003且issueFlag=Y
                        // 1.2.1.1   佣金变更插入一条数据
//                        User user = userMapper.selectUserId(user_id);
//                        MessageMoney message = new MessageMoney();
//                        message.setMoney(0);
//                        message.setOrder_id(id);
//                        message.setOrder_type(10);
//                        message.setOrigin_id(user.getId());
//                        message.setRake_money(bonus);
//                        message.setUser_id(user_id);
//                        message.setMessage_type(1);
//                        userMoneyMapper.insertMessageMoney(message);
//
//                      //1.2.1.2  修改用户 用户普通金额预估,普通佣金累计收益
//                        UserMoney userMoney = new UserMoney();
//                        userMoney.setUser_id(user_id);
////                        userMoney.setOwner_estimate(bonus);
//                        userMoney.setAccumulated(bonus);
//                        userMoneyMapper.updateUserMoney(userMoney);
//
//                      //1.2.1.3  激光推送
//                        if (user_id == user.getId()) {
//                            moneyService.addCreditCardMessageRakeMoney(Integer.parseInt(supplierCustNo), bonus, id, creditCardOrder.getBank_name());
//                        }
                        System.out.println("订单存在-订单与数据库不相同:根据状态更新并推送激光");
                    }
                }
                System.out.println("订单存在-订单与数据库相同:");


                //返佣流程
                //存在的话直接 更新
                String orderId = id;
                Order order = orderMapper.getRepeatOrder(orderId);
                Map map = new HashMap();
                map.put("order_id", orderId);
                /***
                 * 卡多分订单状态： 000 老户订单 001 带查询 002审核中 003审核通过 004 审核拒绝 005 未完成 006 异常订单
                 *
                 * jz_order 订单状态： 1-订单结算 2-订单付款 3-订单未付款 4-订单失效
                 *            当type = 10   ,1订单结算 2 审核通过，3 审核中 ， 4 审核不 通过 5带查询  6未完成7 异常订单 8 失效订单
                 * */
                if (applyStatus.equals("000") || applyStatus.equals("005")) {
                    map.put("status", 6);
                } else if (applyStatus.equals("001")) {
                    map.put("status", 5);
                } else if (applyStatus.equals("002")) {
                    map.put("status", 3);
                } else if (applyStatus.equals("003")) {
                    map.put("status", 2);
                } else if (applyStatus.equals("004")) {
                    map.put("status", 4);
                } else if (applyStatus.equals("006")) {
                    map.put("status", 7);
                } else {
                    map.put("status", 8);
                }
                logger.info("核桃省钱开始更新卡多分信用卡的订单【" + orderId + "】...");
                if (order.getStatus() != 2) { //当前订单没有结算  则更新
                    orderMapper.updateOrder(map);//改走order 更新，有改动增加字段
                    Map mapuser = new HashMap();
                    int userid = order.getUser_id();
                    mapuser.put("id", userid);
                    User user = userMoneyMapper.getByUserId(mapuser);
                    order.setStatus((Integer) map.get("status"));
                    moneyService.updateOrderFansRake(user, order);
                }
                System.out.println("修改返佣逻辑走完");
            }
        } catch (Exception e) {

        } finally {
            outSteam.close();
            inStream.close();
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    @Override
    public void synchronizationCreditCardOrder(String userId, String orderId) {
//        Map<String, Object> map = new HashMap<String, Object>();
//
//        map.put("custNo", orderId);
//        map.put("supplierCustNo", userId);
//        map.put("createDatetime", createDatetime);
//        CreditCardOrder creditCardOrder = creditCardOrderMapper.selectAll(map);
//
//        //减少用户普通金额预估  增加余额
//        UserMoney userMoney = new UserMoney();
//        userMoney.setUser_id(Integer.parseInt(userId));
//        userMoney.setOwner_estimate(0 - creditCardOrder.getBonus());
//        userMoney.setNormal_balance(creditCardOrder.getBonus());
//        userMoneyMapper.updateUserMoney(userMoney);
//        System.out.println("信用卡订单已结算！");

        Order order = commonMapper.getOrderInfo(orderId);
        if (null != order && order.getStatus() != 1) {
            Map mapuser = new HashMap();
            int userid = order.getUser_id();
            mapuser.put("id", userid);
            User user = userMoneyMapper.getByUserId(mapuser);
            //更新订单状态
            Map map = new HashMap();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(new Date()).toString();
            map.put("order_id", orderId);
            map.put("rake_back", order.getRake_back());
            map.put("user_rake", order.getUser_rake());
            map.put("user_rake_back", order.getUser_rake_back());
            map.put("clear_time", time);
            map.put("status", 1);
            commonMapper.updateOrder(map);//更新order表  返佣
            order.setStatus(1);//结算状态
            moneyService.updateOrderFansRake(user, order);
        }
    }

    /***
     * 请求 卡多分
     * @param json 对应接口参数集合
     * @param url 接口名称
     * */
    private String getData(JSONObject json, String url) {
        //渠道号，对接邮件中的appKey
        String supplierCode = appkey;

        //方法地址，文档中请求地址从'/b2b'开始，截取到最后，用于获取sign
        String urlpath = url;

        //paramMap,用于获取sign,固定代码
        Map<String, String> paramMap = new HashMap<String, String>();
        String timestamp = String.valueOf(System.currentTimeMillis());
        paramMap.put("X-BEISHENG-Auth-Timestamp", timestamp);

        //请求参数,json格式,必须排序,按照treeMap自然排序
        //建议参数先放入treeMap中，然后转成json字符串
        String bodyContent = json.toJSONString();

        //盐值，用于获取sign，值和supplierCode一致
        String salt = supplierCode;

        //获取sign
        String sign = "";
        try {
            sign = ClientAuthorizationUtil.hmacSHA1(salt, urlpath, paramMap, bodyContent);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

//        System.out.println("最终加密sign：" + sign);

        //组装请求头部map
        Map<String, String> headerMap = new HashMap<String, String>();
        headerMap.put("authorization", "BEISHENG " + supplierCode + ":" + sign);
        headerMap.put("X-BEISHENG-Auth-Timestamp", timestamp);

        //请求接口
        return sendPost(apiUrl + urlpath, bodyContent, headerMap);
    }


    @Override
    public Tip creditCardOrderAll(String user_id, String token_id, String status) {
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(token_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        Page page = new Page(1, 10);
        Map<String, String> map = new HashMap<String, String>();
        map.put("user_id", user_id);
        map.put("status", status);
        List<CreditCardOrderDTO> creditCardOrders = creditCardOrderMapper.selectList(page, map);
        page.setRecords(creditCardOrders);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), page);
    }

    public Tip finDetail(String id){
        CreditCardOrder creditCardOrde =creditCardOrderMapper .finDetail(Integer.parseInt(id));
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), creditCardOrde);
    }
}
